import React, { useEffect, useState } from 'react';
import orgCtrl from '@/ts/controller';
import { MallTemplate } from '@/executor/open/mallTemplate/pages';
import { DashboardTemplateHomeView } from '@/executor/open/dashboardTemplate';
import { IMallTemplate } from '@/ts/core/thing/standard/page/mallTemplate';
import { TotalView } from '@/ts/core/thing/standard/view/totalView';
import LedgerForm from '@/executor/open/view/ledger/LedgerForm';
import { IView, IEntity } from '@/ts/core';
import Banner from '@/components/DataPreview/session/WorkBench/components/Banner';
import cls from './index.module.less';
import { Descriptions, Tooltip, Space, Empty } from 'antd';
import EntityIcon from '@/components/Common/GlobalComps/entityIcon';
import { executeCmd } from '@/executor/action';
import { ViewerHost } from '@/executor/open/page/view/ViewerHost';
import ViewerManager from '@/executor/open/page/view/ViewerManager';
import { IElementHost } from '@/ts/element/standard';
import ViewProvider from '@/ts/core/provider/view';
import dxScrollView from 'devextreme/ui/scroll_view';
import { ScrollView } from 'devextreme-react';
import ActivityMessage from '@/components/TargetActivity/ActivityMessage';
import activityEmptyImg from '/img/empty/noactivity.png';
import { useHistory } from 'react-router-dom';
import TypeIcon from '@/components/Common/GlobalComps/typeIcon';
import { viewEntity } from '@/ts/base/schema';

// 在 View 组件外部定义：
const RenderActive: React.FC<{ view: ViewProvider }> = ({ view }) => {
  const [actionKey] = useState<number>(1);
  const [actionList, setActionList] = useState<any[]>([]);
  const [isLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const loadMoreActivity = async (component: dxScrollView | undefined) => {
    const news = await view.load(10);
    setActionList([...actionList, ...news]);
    if (component) {
      setHasMore(false);
      await component.release(news.length < 10);
    }
  };

  return (
    <div className={cls.activityList}>
      <ScrollView
        key={actionKey}
        bounceEnabled
        height={300}
        reachBottomText={hasMore ? '加载更多...' : ''}
        onReachBottom={(e) => loadMoreActivity(e.component)}
        onInitialized={(e) => loadMoreActivity(e.component)}>
        <div className={cls.actionList}>
          {isLoading && actionList.length === 0 ? (
            <div>加载中...</div>
          ) : actionList.length > 0 ? (
            <>
              {actionList.map((actionItem) => (
                <div className={cls.actionBody}>
                  <ActivityMessage
                    key={actionItem.key}
                    item={actionItem}
                    activity={view.metdata as any}
                    hideResource={true}
                  />
                </div>
              ))}
            </>
          ) : (
            <div className={cls.emptyList}>
              <Empty description={false} image={activityEmptyImg} />
            </div>
          )}
        </div>
      </ScrollView>
    </div>
  );
};
const View: React.FC = () => {
  const history = useHistory();
  if (!orgCtrl.viewEntity?.entity) {
    history.push('/home');
  }
  
  const [view, setView] = useState<ViewProvider | null>(null);
  const [entity] = useState<any>(orgCtrl?.viewEntity?.entity);
  const [selected, setSelected] = useState<any>();
  const [templates, setTemplates] = React.useState<any[]>([]);
  useEffect(() => {
    const currentEntity = orgCtrl.viewEntity?.entity;
    if (currentEntity) {
      ViewProvider.resetInstance();
      const newView = ViewProvider.getInstance(currentEntity);
      setView(newView);
    } else {
      setView(null);
    }
    loadTemps();
  }, [orgCtrl.viewEntity?.entity]);
  
  const loadTemps = async () => {
    setTemplates([
      {
        id: '1',
        name: '动态',
        typeName: '动态',
      },
    ]);
    setSelected({
      id: '1',
      name: '动态',
      typeName: '动态',
    });
  };
  const renderBanner = () => {
    return (
      <div className={cls.banner}>
        <Banner space={'' as any} bannerkey="workBench" />
      </div>
    );
  };
  const renderDataCore = () => {
    return (
      <div className={cls.baseData}>
        <div className={cls.companyEntity}>
          <EntityIcon entity={entity} size={50} />
          <div className={cls.name}>{entity.name}</div>
          <div
            className={cls.lookQr}
            onClick={() => {
              executeCmd('qrcode', orgCtrl.viewEntity);
            }}>
            <TypeIcon iconType={'qrcode'} size={16} />
            <span>查看二维码</span>
          </div>
        </div>
        <Descriptions
          column={1}
          colon={false}
          labelStyle={{ width: '100px', color: '#6F7686' }}>
          <Descriptions.Item label="名称">{entity.name}</Descriptions.Item>
          <Descriptions.Item label="归属">{entity.belongId}</Descriptions.Item>
          <Descriptions.Item label="代码">{entity.code}</Descriptions.Item>
        </Descriptions>
        <Descriptions
          column={1}
          colon={false}
          labelStyle={{ width: '100px', color: '#6F7686' }}>
          <Descriptions.Item label="当前数据核">
            <EntityIcon entityId={entity.storeId as string} showName />
          </Descriptions.Item>
          <Descriptions.Item label="简介">
            <Tooltip
              title={entity.remark}
              overlayStyle={{ maxWidth: 600 }}
              mouseEnterDelay={0.3}>
              <div className={cls.remark}>{entity.remark}</div>
            </Tooltip>
          </Descriptions.Item>
        </Descriptions>
      </div>
    );
  };

  const renderEntity = (entity: IEntity<any> = selected) => {
    switch (entity.typeName) {
      case '动态':
        return view ? <RenderActive view={view} /> : <></>;
      case '页面模板':
        return (
          <ViewerHost
            ctx={{
              view: new ViewerManager(entity as IElementHost<any>),
            }}
          />
        );
      case '视图':
        if (entity.groupTags.includes('图表视图')) {
          return <DashboardTemplateHomeView current={entity as any} />;
        } else if (entity instanceof TotalView) {
          return (
            <LedgerForm
              isFull={false}
              current={entity as IView}
              form={entity.metadata as any}
              directory={entity.directory}
            />
          );
        } else {
          return <>暂不支持</>;
        }
      case '商城模板':
        return <MallTemplate current={entity as IMallTemplate} />;
      default:
        return <>暂不支持</>;
    }
  };
  return (
    <div className={cls.viewStyle}>
      {renderBanner()}
      {renderDataCore()}
      <div className={cls.portalPage}>
        <div className="workbench-content portal-page">
          <Space direction="horizontal" size={10}>
            {templates.map((item, idx) => (
              <a
                key={idx}
                onClick={() => setSelected(item)}
                className={`navbar-item ${
                  selected?.id === item.id ? 'navbar-item_selected' : ''
                }`}>
                <span className="navbar-item-text">{item.name}</span>
              </a>
            ))}
          </Space>
        </div>
      </div>
      <div className={cls.portalPageBody}>
        {selected?.id && view && renderEntity(selected.file)}
      </div>
    </div>
  );
};
export default View;
